import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../models/project_config.dart';
import '../models/unified_config.dart';

class ConfigService {
  static ConfigService? _instance;
  late SharedPreferences _prefs;

  ConfigService._();

  static Future<ConfigService> getInstance() async {
    if (_instance == null) {
      _instance = ConfigService._();
      await _instance!._init();
    }
    return _instance!;
  }

  Future<void> _init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // ============ 统一配置管理 ============

  // 保存统一配置
  Future<void> saveUnifiedConfig(UnifiedConfig config) async {
    final jsonString = jsonEncode(config.toJson());
    await _prefs.setString('unified_config', jsonString);
  }

  // 加载统一配置
  Future<UnifiedConfig> loadUnifiedConfig() async {
    final jsonString = _prefs.getString('unified_config');
    if (jsonString != null) {
      final jsonMap = jsonDecode(jsonString);
      return UnifiedConfig.fromJson(jsonMap);
    }
    return UnifiedConfig();
  }

  // 清除统一配置
  Future<void> clearUnifiedConfig() async {
    await _prefs.remove('unified_config');
  }

  // ============ 兼容性支持（旧版本配置） ============

  // 保存项目配置（保持兼容性）
  Future<void> saveConfig(ProjectConfig config) async {
    final jsonString = jsonEncode(config.toJson());
    await _prefs.setString('project_config', jsonString);
  }

  // 加载项目配置（保持兼容性）
  Future<ProjectConfig> loadConfig() async {
    final jsonString = _prefs.getString('project_config');
    if (jsonString != null) {
      final jsonMap = jsonDecode(jsonString);
      return ProjectConfig.fromJson(jsonMap);
    }
    return ProjectConfig();
  }

  // 清除配置（保持兼容性）
  Future<void> clearConfig() async {
    await _prefs.remove('project_config');
  }

  // ============ 配置迁移 ============

  // 从旧配置迁移到统一配置
  Future<UnifiedConfig> migrateFromOldConfig() async {
    final oldConfig = await loadConfig();
    final unifiedConfig = UnifiedConfig();

    // 迁移基本信息
    unifiedConfig.projectPath = oldConfig.projectPath;
    unifiedConfig.projectName = oldConfig.projectName;
    unifiedConfig.version = oldConfig.version;
    unifiedConfig.company = oldConfig.companyName;
    unifiedConfig.description = oldConfig.description;
    unifiedConfig.iconPath = oldConfig.iconPath;
    unifiedConfig.outputDir = oldConfig.outputDir;
    // 转换构建模式 - 从字符串转换为枚举
    if (oldConfig.buildMode != null) {
      switch (oldConfig.buildMode.toString()) {
        case 'BuildMode.standalone':
          unifiedConfig.buildMode = BuildMode.standalone;
          break;
        case 'BuildMode.onefile':
          unifiedConfig.buildMode = BuildMode.onefile;
          break;
        case 'BuildMode.module':
          unifiedConfig.buildMode = BuildMode.module;
          break;
        default:
          unifiedConfig.buildMode = BuildMode.standalone;
      }
    } else {
      unifiedConfig.buildMode = BuildMode.standalone;
    }

    // 保存迁移后的配置
    await saveUnifiedConfig(unifiedConfig);

    // 清除旧配置
    await clearConfig();

    return unifiedConfig;
  }

  // 检查是否需要迁移
  Future<bool> needsMigration() async {
    final hasOldConfig = _prefs.containsKey('project_config');
    final hasNewConfig = _prefs.containsKey('unified_config');
    return hasOldConfig && !hasNewConfig;
  }
}
